﻿using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Orm.DataEntity;

namespace RK.FormPlugin.Dz
{
    [Description("表单插件:自动下推示例"), HotUpdate]
    public class DzConvert : AbstractDynamicFormPlugIn
    {
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            // 获取源单与目标单直接的转换规则，如果规则未启用，则返回为空，注意容错
            // 假设：上游单据FormId为sourceFormId，下游单据FormId为targetFormId
            string sourceFormId = "";
            string targetFormId = "";
            var rules = ConvertServiceHelper.GetConvertRules(this.Context, sourceFormId, targetFormId);
            var rule = rules.FirstOrDefault(r => r.IsDefault);

            // 获取在列表上当前选择需下推的行
            ListSelectedRow[] selectedRows = ((IListView)this.View).SelectedRowsInfo.ToArray();
            // 调用下推服务，生成下游单据数据包
            ConvertOperationResult operationResult = null;
            Dictionary<string, object> custParams = new Dictionary<string, object>();
            try
            {
                PushArgs pushArgs = new PushArgs(rule, selectedRows)
                {
                    TargetBillTypeId = "",                 // 请设定目标单据单据类型。如无单据类型，可以空字符
                    TargetOrgId = 0,                        // 请设定目标单据主业务组织。如无主业务组织，可以为0
                    CustomParams = custParams,  // 可以传递额外附加的参数给单据转换插件，如无此需求，可忽略
                };
                //执行下推操作，并获取下推结果
                operationResult = ConvertServiceHelper.Push(this.View.Context, pushArgs, OperateOption.Create());
            }
            catch (KDExceptionValidate ex)
            {
                this.View.ShowErrMessage(ex.Message, ex.ValidateString);
            }
            catch (KDException ex)
            {
                this.View.ShowErrMessage(ex.Message);
            }
            catch
            {
                throw;
            }
            // 获取生成的目标单据数据包
            DynamicObject[] objs = (from p in operationResult.TargetDataEntities
                                    select p.DataEntity).ToArray();
            // 读取目标单据元数据
            var targetBillMeta = MetaDataServiceHelper.Load(this.View.Context, targetFormId) as FormMetadata;
            // 提交数据库保存，并获取保存结果
            var saveResult = BusinessDataServiceHelper.Save(this.View.Context, targetBillMeta.BusinessInfo, objs);

        }
    }
}
